import 'package:flutter_bili_app/http/core/hi_adapter.dart';
import 'package:flutter_bili_app/http/core/hi_error.dart';
import 'package:flutter_bili_app/http/request/base_request.dart';
import 'package:flutter_bili_app/http/request/http_method.dart';
import 'package:dio/dio.dart';

class DioAdapter extends HiNetAdapter {
  var dio=Dio();
  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    var response;
    var error;
    try {
      var options = Options(headers: request.getAllHeader());
      if (request.getHttpMethod() == HttpMethod.GET) {
        response = await dio.get(request.requestUrl(), options: options,data: request.data,queryParameters: request.queryParameters);
      } else if (request.getHttpMethod() == HttpMethod.POST) {
        response = await dio.post(request.requestUrl(), options: options,
            data:request.getFromData() == null ? request.data : FormData.fromMap(request.getFromData()!),
            queryParameters: request.queryParameters);
      } else if (request.getHttpMethod() == HttpMethod.DELETE) {
        response = await dio.post(request.requestUrl(), options: options,
            data:request.getFromData() == null ? request.data : FormData.fromMap(request.getFromData()!),
            queryParameters: request.queryParameters);
      }
    } on DioException catch (e) {
      error = e;
      response = e.response;
    }
    if(error !=null){
      throw (HiNetError(response.statusCode,error.toString(),data: await buildRes(response,request)));
    }
    return await  buildRes(response, request);
  }

  buildRes(Response? response, BaseRequest request) {
    return Future.value(HiNetResponse(data:response?.data,request: request,statusCode: response?.statusCode,statusMessage: response?.statusMessage,extra: response));
  }
}
